package nina.yiyou.salary.input.info

import nina.yiyou.salary.input.util.CellValueGetter
import nina.yiyou.salary.input.util.ExcelReadOpener
import nina.yiyou.salary.input.util.HeaderMapMaker
import org.apache.poi.ss.usermodel.Row
import org.apache.poi.ss.usermodel.Sheet
import org.apache.poi.ss.usermodel.Workbook

class EtcExcelReader {

  EtcExcelReader(String excelPath) {
    _excelPath = excelPath
  }

  Map<String, Map> read() {
    Workbook workbook = new ExcelReadOpener(_excelPath).openXlsx()
    def result = readResultMap(workbook.getSheetAt(0))
    workbook.close()
    return result
  }

  private Map<String, Map> readResultMap(Sheet sheet) {
    Map<Integer, String> header = new HeaderMapMaker(sheet.getRow(0)).make()
    def getCell = { Row row, int col -> new CellValueGetter(row.getCell(col)).get() }

    String idKey = header[0]
    return (1..sheet.lastRowNum)
        .collect { sheet.getRow(it) }
        .collect { header.collectEntries { col, head -> [head, getCell(it, col)] } as Map }
        .collectEntries { [it[idKey], it] }
  }

  private final String _excelPath
}
